package com.id.sigma;

import javassist.expr.NewArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.json.simple.*;
import org.json.simple.parser.*;
@Controller
@RequestMapping(value = "/core", method = RequestMethod.GET)
public class CoreController {

	@RequestMapping(value = "/showAllBroker", method = RequestMethod.GET)
	public ModelAndView showAllBroker(@ModelAttribute("Method") String method,
			Model model) {
		return new ModelAndView("JSON", "json",ManageBrokeSingleton.getInstance().listBrokers());
		// return new ModelAndView("trainee");
	}

	@RequestMapping(value = "/broker/get/id/{id}", method = RequestMethod.GET)
	public ModelAndView getBrooker(@PathVariable("id") Integer id,
			Model model) {
		return new ModelAndView("JSON", "json", ManageBrokeSingleton.getInstance().getBroker(id));
	}

	@RequestMapping(value = "/broker/create/json/{json}", method = RequestMethod.GET)
	public ModelAndView createBroker(
			@PathVariable("json") String json) {
		System.out.println("create");
		JSONParser parser=new JSONParser();
		JSONObject obj=null;
		try {
			obj = (JSONObject)parser.parse(json);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String msg=ManageBrokeSingleton.getInstance().addBroker( Integer.parseInt(((Long)obj.get("idBroker")).toString()), (String)obj.get("namaBroker"), (String)obj.get("alamat"), Long.valueOf((String)obj.get("saldoUang")),Long.valueOf((String)obj.get("saldoSaham")));
		return new ModelAndView("JSON", "json",msg);
	}
	@RequestMapping(value = "/broker/update/json/{json}", method = RequestMethod.GET)
	public ModelAndView updateBroker(
			@PathVariable("json") String json) {
		System.out.println("create");
		JSONParser parser=new JSONParser();
		JSONObject obj=null;
		try {
			obj = (JSONObject)parser.parse(json);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String msg=ManageBrokeSingleton.getInstance().updateBrokers(Integer.parseInt(((Long)obj.get("idBroker")).toString()), (String)obj.get("namaBroker"), (String)obj.get("alamat"), (Long)obj.get("saldoUang"),(Long)obj.get("saldoSaham"));
		return new ModelAndView("JSON", "json",msg);
	}

	@RequestMapping(value = "/broker/delete/id/{id}", method = RequestMethod.GET)
	public ModelAndView deleteBroker(@PathVariable("id") Integer id,
			Model model) {
		String msg=ManageBrokeSingleton.getInstance().deleteBroker(id);
		return new ModelAndView("JSON", "json", msg);
	}
}
